<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="registrationPatientName">
        <el-input
          v-model="queryParams.registrationPatientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="registrationStatus">
        <el-select v-model="queryParams.registrationStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.his_reg_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>




      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="newregistrationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者姓名" align="center" prop="registrationPatientName" />
      <el-table-column label="挂号科室" align="center">
      <template slot-scope="scope">
        {{ getDeptName(scope.row.registrationDeptId) }}
      </template>
    </el-table-column>
      <el-table-column label="挂号医生" align="center" prop="registrationDoctorName" />
      <el-table-column label="挂号日期" align="center" prop="registrationSchedule" />
      <el-table-column label="状态" align="center" prop="registrationStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_reg_status" :value="scope.row.registrationStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
  <template slot-scope="scope">
    <!-- 状态为1时显示查看详情 -->
    <el-button
      v-if="scope.row.registrationStatus == '2'|| scope.row.registrationStatus == '5'"
      size="mini"
      type="text"
      icon="el-icon-view"
      @click="handleDetail(scope.row)"
    >查看详情</el-button>

    <!-- 状态为2时显示退号 -->
    <el-button
      v-if="scope.row.registrationStatus == '1'"
      size="mini"
      type="text"
      icon="el-icon-delete"
      @click="handleCancel(scope.row)"
      style="color: #F56C6C"
    >退号</el-button>
  </template>
</el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改newregistration对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者ID" prop="registrationPatientId">
          <el-input v-model="form.registrationPatientId" placeholder="请输入患者ID" />
        </el-form-item>
        <el-form-item label="挂号日期" prop="registrationSchedule">
          <el-input v-model="form.registrationSchedule" placeholder="请输入挂号日期" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.registrationStatus">
            <el-radio
              v-for="dict in dict.type.his_reg_status"
              :key="dict.value"
:label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="患者姓名" prop="registrationPatientName">
          <el-input v-model="form.registrationPatientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="挂号科室ID
" prop="registrationDeptId">
          <el-input v-model="form.registrationDeptId" placeholder="请输入挂号科室ID
" />
        </el-form-item>
        <el-form-item label="挂号医生ID" prop="registrationDoctorId">
          <el-input v-model="form.registrationDoctorId" placeholder="请输入挂号医生ID" />
        </el-form-item>
        <el-form-item label="挂号医生姓名" prop="registrationDoctorName">
          <el-input v-model="form.registrationDoctorName" placeholder="请输入挂号医生姓名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 就诊详情 -->
    <el-dialog title="就诊详情" :visible.sync="detailVisible" width="80%">
      <el-card>
        <el-tabs v-model="activeName2" type="border-card">


        <el-tab-pane label="病例详情" name="first">
          <el-form ref="form" :model="detailData"  label-width="200px">
                                <el-form-item label="病例编号" prop="treatID" >
                                    <el-input v-model="detailData.treatId" placeholder="保存后获取病例编号" readonly  style="width: 200px"/>
                                </el-form-item>
                                <el-form-item label="发病日期" prop="treatDate">
                                    <el-date-picker clearable v-model="detailData.treatDate" type="date"
                                        value-format="yyyy-MM-dd" placeholder="请选择就诊日期" readonly>
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="是否传染" prop="treatContagion">
                                    <el-select v-model="detailData.treatContagion" placeholder="请选择是否传染" clearable readonly >
                                        <el-option v-for="dict in dict.type.his_treat_contagion" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="主诉" prop="treatComplaint">
                                    <el-input v-model="detailData.treatComplaint" placeholder="请输入主诉" type="textarea"
                                        maxlength="100" show-word-limit readonly />
                                </el-form-item>
                                <el-form-item label="诊断信息" prop="info">
                                    <el-input v-model="detailData.treatInfo" placeholder="请输入诊断信息" type="textarea"
                                        maxlength="100" show-word-limit readonly />
                                </el-form-item>
                                <el-form-item label="医生建议" prop="treatAdvice">
                                    <el-input v-model="detailData.treatAdvice" placeholder="请输入医生建议" type="textarea"
                                        maxlength="100" show-word-limit readonly />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="detailData.remark" placeholder="请输入备注" type="textarea"
                                        maxlength="250" show-word-limit readonly />
                                </el-form-item>
          </el-form>


        </el-tab-pane>

        <el-tab-pane label="处方详情">
          <el-table :data="prescriptionData" stripe border style="width: 100%">
                                <el-table-column label="编号" align="center" prop="treatId" />
                                <el-table-column label="名称" align="center" prop="prescriptionName" />
                                <el-table-column label="数量" align="center" prop="quantity" />
                                <el-table-column label="总价" align="center" prop="amount" />
                            </el-table>

                         <!-- 添加缴费操作栏 -->
                        <div style="margin-top: 20px;text-align: right">
                          <el-button
                            v-if="currentRow.registrationStatus == '2'"
                            type="primary"
                            @click="handlePay"
                          >去缴费</el-button>
                        </div>
        </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-dialog>

    <!-- 添加缴费对话框 -->
    <el-dialog title="门诊缴费" :visible.sync="payVisible" width="30%">
      <div style="font-size: 18px">
        <p>总金额：<span style="color:red">{{ totalAmount }}元</span></p>
      </div>
      <div slot="footer">
        <el-button @click="payVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确认支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNewregistration, getNewregistration, delNewregistration, addNewregistration, updateNewregistration,getListByPatientId } from "@/api/his/newregistration";
import{ getUserProfile} from "@/api/system/user";
import { listTreat, addTreat, updateTreat ,getTreat} from "@/api/his/treat";
import { listNewprescription, getNewprescription, delNewprescription, addNewprescription, updateNewprescription,getNewone,getListByTreatId } from "@/api/his/newhisprescription";
import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/his/patient";
import { listDept,getDept} from "@/api/his/dept";
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine ,reduceStock} from "@/api/his/medicine";

export default {
  name: "Newregistration",
  dicts: ['his_reg_status','his_treat_contagion'],
  data() {
    return {
      payVisible: false,
      totalAmount: 0,
      activeName2: 'first',
      currentRow: {},
      detailVisible: false,
      detailData: {
      //根据病例详情创建测试数据
        treatId: "",
        treatDate: "",
        treatContagion: "",
        treatComplaint: "",
        treatInfo: "",
        treatAdvice: "",
        remark: ""
      }, // 详情数据
    prescriptionData: [], // 处方数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // newregistration表格数据
      newregistrationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registrationPatientId: null,
        registrationSchedule: null,
        registrationStatus: null,
        registrationPatientName: null,
        registrationDeptId: null,
        registrationDoctorId: null,
        registrationDoctorName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        registrationPatientId: [
          { required: true, message: "患者ID不能为空", trigger: "blur" }
        ],
        registrationSchedule: [
          { required: true, message: "挂号日期不能为空", trigger: "blur" }
        ],
        registrationStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
      },
      patientList: [],
      list :[],
      deptOptions: [],
      
    };
  },
  created() {
    this.queryParams.registrationSchedule = this.getCurrentDate();
    this.queryParams.patienUsername = this.$store.state.user.name;
    this.getqList();
    listDept().then(response => {
        this.deptOptions = response.rows;
      });
   
    
  },
  methods: {
      // 根据科室ID获取科室名称
  getDeptName(deptId) {
    const dept = this.deptOptions.find(dept => dept.deptId === deptId);
    return dept ? dept.deptName : '未知科室';
  },
    getqList() {
      this.loading = true;
      listPatient(this.queryParams).then(response => {
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.list = this.patientList.map(patient => patient.patientId);
        this.getList(this.list);
        console.log();
        console.log(this.patientList);
      });
    },
    confirmPay() {
    updateNewregistration({
      registrationId: this.currentRow.registrationId,
      registrationStatus: '5' // 假设3是已缴费状态
    }).then(() => {
       // 调用减少库存的方法
      this.reduceInventory()
      this.$message.success('缴费成功')
      this.payVisible = false
      this.getqList() // 刷新列表
      this.detailVisible = false // 关闭详情弹窗
    })
  },
  reduceInventory() {
  // 假设你有一个方法来获取需要减少库存的药品信息
  const prescriptionData = this.prescriptionData

  // 遍历处方数据并减少库存
  prescriptionData.forEach(prescription => {
    const medicineData = {
      medicineId: prescription.prescriptionId, // 假设 prescriptionName 是药品ID
      stock: prescription.quantity // 减少的数量
    }

    reduceStock(medicineData).then(response => {
 
    })
   
   
  })
},
     // 计算总价
  calculateTotal() {
    return this.prescriptionData.reduce((total, item) => {
      return total + ((item.amount)*(item.quantity) || 0)
    }, 0).toFixed(2)
  },
    handlePay() {
    this.totalAmount = this.calculateTotal()
    this.payVisible = true
  },
    getListByTreatIdinfo(treatId){
      getListByTreatId(treatId).then(response => {
        this.prescriptionData = response.data;
      });
    },
    getTreatInfo(treatId){
      getTreat(treatId).then(response => {
        this.detailData = response.data;
      });
    },
    async handleDetail(row) {
    try {
     this.getTreatInfo(row.treatId);
     this.getListByTreatIdinfo(row.treatId);
      this.detailVisible = true;
      this.currentRow = row;
    } catch (error) {
      this.$message.error('数据加载失败');
      console.error('详情加载错误:', error);
    }
  },
     // 退号操作
  handleCancel(row) {
    this.$confirm('确定要退号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      updateNewregistration({
        registrationId: row.registrationId,
        registrationStatus: '3' // 假设3是退号状态
      }).then(() => {
        this.$message.success('退号成功');
        this.getqList();
      });
    });
  },
      // 获取当前日期（格式：YYYY-MM-DD）
  getCurrentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
    /** 查询newregistration列表 */
    getList(list) {
      this.loading = true;
      getListByPatientId(list).then(response => {
        this.newregistrationList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        registrationId: null,
        registrationPatientId: null,
        registrationSchedule: null,
        registrationStatus: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        registrationPatientName: null,
        registrationDeptId: null,
        registrationDoctorId: null,
        registrationDoctorName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getqList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.registrationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加newregistration";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const registrationId = row.registrationId || this.ids
      getNewregistration(registrationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改newregistration";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.registrationId != null) {
            updateNewregistration(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getqList();
            });
          } else {
            addNewregistration(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getqList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const registrationIds = row.registrationId || this.ids;
      this.$modal.confirm('是否确认删除newregistration编号为"' + registrationIds + '"的数据项？').then(function() {
        return delNewregistration(registrationIds);
      }).then(() => {
        this.getqList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('newregistration/newregistration/export', {
        ...this.queryParams
      }, `newregistration_${new Date().getTime()}.xlsx`)
    },
    // 根据登录ID获取登录用户详情信息
    getUserInfo() {
        getUserProfile().then(response => {
        this.queryParams.doctName = response.data.nickName;
        this.getqList();
        console.log(response);
      });
    },
  }
};
</script>
